package com.zjj.algorithm.learning.leetcode.tree;

/**
 * 226. 翻转二叉树 简单题
 * 给你一棵二叉树的根节点 root ，翻转这棵二叉树，并返回其根节点。
 * <p>
 * 输入：root = [4,2,7,1,3,6,9]
 * 输出：[4,7,2,9,6,3,1]
 * <p>
 * 输入：root = [2,1,3]
 * 输出：[2,3,1]
 * 示例 3：
 * <p>
 * 输入：root = []
 * 输出：[]
 * <p>
 * <p>
 * 提示：
 * <p>
 * 树中节点数目范围在 [0, 100] 内
 * -100 <= Node.val <= 100
 *
 * @author zjj_admin
 * @date 2022/12/5 13:53
 */
public class InvertBinaryTree {

    public static void main(String[] args) {

        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node3 = new TreeNode(3);

        node1.left = node2;
        node1.right = node3;

        invertTree(node1);
        System.out.println("node3 = " + node3);
    }


    /**
     * 反转二叉树
     * <p>
     * 时间
     * 0 ms
     * 击败
     * 100%
     * 内存
     * 38.9 MB
     * 击败
     * 66.58%
     *
     * @param root
     * @return
     */
    public static TreeNode invertTree(TreeNode root) {
        if (root == null) {
            return null;
        }
        if (root.left != null && root.right != null) {
            TreeNode temp;
            temp = root.right;
            root.right = root.left;
            root.left = temp;

            invertTree(root.left);
            invertTree(root.right);
        } else if (root.left != null) {
            root.right = root.left;
            root.left = null;
            invertTree(root.right);
        } else if (root.right != null) {
            root.left = root.right;
            root.right = null;
            invertTree(root.left);
        }
        return root;
    }
}
